package com.xnyzc.lhy.mis.service.impl.worksheet;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.component.config.security.TokenUser;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.entity.ParameterEnum;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.exception.WorksheetException;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.order.EBillType;
import com.xnyzc.lhy.common.util.*;
import com.xnyzc.lhy.mis.entity.area.DidiSysArea;
import com.xnyzc.lhy.mis.entity.area.OaSysArea;
import com.xnyzc.lhy.mis.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.mis.entity.param.cms.PageDTO;
import com.xnyzc.lhy.mis.entity.param.worksheet.WorkSheetGetByConditions;
import com.xnyzc.lhy.mis.entity.param.worksheet.didi.CreateWorkOrderParam;
import com.xnyzc.lhy.mis.entity.param.worksheet.didi.CreateWorkResult;
import com.xnyzc.lhy.mis.entity.param.worksheet.didi.UpdateWorkOrderParam;
import com.xnyzc.lhy.mis.entity.param.worksheet.didi.WorkOrderUrgentParam;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.mis.entity.system.OaSysUser;
import com.xnyzc.lhy.mis.entity.user.OaDUser;
import com.xnyzc.lhy.mis.entity.vehicle.OaSysVehicle;
import com.xnyzc.lhy.mis.entity.wallet.OaDFreeze;
import com.xnyzc.lhy.mis.entity.worksheet.OaCWorkOrder;
import com.xnyzc.lhy.mis.entity.worksheet.OaSysWorksheet;
import com.xnyzc.lhy.mis.feign.heli.WorkSheetToHeLiService;
import com.xnyzc.lhy.mis.mapper.area.DidiSysAreaMapper;
import com.xnyzc.lhy.mis.mapper.area.OaSysAreaMapper;
import com.xnyzc.lhy.mis.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.mis.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysUserMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaSysVehicleMapper;
import com.xnyzc.lhy.mis.mapper.wallet.OaDFreezeMapper;
import com.xnyzc.lhy.mis.mapper.worksheet.OaCWorkOrderMapper;
import com.xnyzc.lhy.mis.mapper.worksheet.OaSysWorksheetMapper;
import com.xnyzc.lhy.mis.mapper.worksheet.OaSysWorksheetOperateMapper;
import com.xnyzc.lhy.mis.service.impl.cms.user.wallet.OacRechargeRecordServiceImpl;
import com.xnyzc.lhy.mis.service.user.message.IOaSysMessageService;
import com.xnyzc.lhy.mis.service.worksheet.IOaSysWorksheetOperateService;
import com.xnyzc.lhy.mis.service.worksheet.IOaSysWorksheetService;
import com.xnyzc.lhy.mis.service.worksheet.IWorkOrderService;
import com.xnyzc.lhy.mis.util.PageUtils;
import com.xnyzc.lhy.order.entity.user.message.OaSysMessage;
import com.xnyzc.lhy.resource.entity.worksheet.OaSysWorksheetEntity;
import com.xnyzc.lhy.resource.entity.worksheet.UpdateTicketStatusEntity;
import com.xnyzc.lhy.resource.entity.worksheet.UrgentTicketEntity;
import com.xnyzc.lhy.resource.entity.worksheet.param.heli.LoginSynchronousParam;
import com.xnyzc.lhy.resource.entity.worksheet.param.heli.RoleSynchronousParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 滴滴调用工单相关
 * </p>
 *
 * @author wangshuo
 * @since 2019-10-08
 */
@Service
@Slf4j
@Transactional
public class WorkOrderServiceImpl implements IWorkOrderService {
    private final String FILLING_MONEY_TYPE = "12";
    private final String DEDUCT_MONEY_TYPE = "8";
    private final String FILLING_MONEY_CANCEL_TYPE = "14";
    private final String DEDUCT_MONEY_CANCEL_TYPE = "13";

    @Autowired
    private OaSysWorksheetOperateMapper oaSysWorksheetOperateMapper;

    @Autowired
    private OaSysWorksheetMapper oaSysWorksheetMapper;

    @Autowired
    private WorkSheetToHeLiService workSheetToHeLiService;

    @Autowired
    IOaSysWorksheetOperateService oaSysWorksheetOperateService;

    @Autowired
    IOaSysWorksheetService iOaSysWorksheetService;

    @Autowired
    private DidiSysAreaMapper didiSysAreaMapper;

    @Autowired
    private OaSysAreaMapper oaSysAreaMapper;

    @Autowired
    private OaCWorkOrderMapper oaCWorkOrderMapper;

    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;

    @Autowired
    private OaSysVehicleMapper oaSysVehicleMapper;

    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;

    @Autowired
    private OaSysUserMapper userMapper;

    @Autowired
    private OaDUserMapper oaDUserMapper;

    @Autowired
    private OaDFreezeMapper oaDFreezeMapper;

    @Autowired
    private IOaSysMessageService iOaSysMessageService;


    /**
     * 导出工单信息
     * @param conditions
     * @return
     */
    @Override
    public void exportWorkOrderByConditions(WorkSheetGetByConditions conditions) {
        long userId = TokenUtil.getTokenUserId();
        if(CheckUtil.objIsEmpty(userId)){
            throw PangException.create(EErrorCode.missingArg);
        }
        if(CheckUtil.objIsEmpty(conditions)){
            throw PangException.create(EErrorCode.missingArg);
        }
        String []sheetHead = {"订单号","订单时间","供应商","司机姓名","车牌","创建人","创建时间","工单金额","工单原因","状态"};
        String []fieldNames = {"orderNo","orderTimeStr","officeName","driverName","vehNo","creatorName","createTimeStr","amount","reason","statusStr"};
        QueryWrapper<OaCWorkOrder> queryWrapper = getOaCWorkOrderQueryWrapper(conditions);
        List<OaCWorkOrder> resWorkOrder = oaCWorkOrderMapper.selectList(queryWrapper);
        List<OaCWorkOrder> collect = new ArrayList<>();
        //对时间和状态进行处理
        if(resWorkOrder.size() != 0){
            collect = resWorkOrder.stream().map(item -> {
                String createTime = DateUtil.convertToStringCustom(item.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                String orderTime = DateUtil.convertToStringCustom(item.getOrderTime(), "yyyy-MM-dd HH:mm:ss");
                String statusStr = item.getStatus() == 0 ? "执行" : "撤销";
                item.setStatusStr(statusStr);
                item.setOrderTimeStr(orderTime);
                item.setCreateTimeStr(createTime);
                return item;
            }).collect(Collectors.toList());
        }
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        SXSSFWorkbook workbook = new SXSSFWorkbook(8000);
        PoiUtil.exportExcel(workbook, 0, "sheet1", collect, Arrays.asList(fieldNames),  Arrays.asList(sheetHead));
        //以流输出到浏览器
        PoiUtil.writeToResponse(workbook, request, response, "WorkSheet");
    }

    /**
     * 撤销工单信息
     * @param oaCWorkOrder
     * @return
     */
    @Override
    public Rv revokeWorkSheetInfo(OaCWorkOrder oaCWorkOrder) {
        long userId = TokenUtil.getTokenUserId();
        String tag = TokenUtil.getTag();
        if(CheckUtil.objIsEmpty(userId,tag,oaCWorkOrder.getWorkOrderId(),oaCWorkOrder.getAmount())){
            throw PangException.create(EErrorCode.missingArg);
        }
        oaCWorkOrder.setStatus(1);
        oaCWorkOrder.setUpdateTime(new Date());
        oaCWorkOrder.setUpdateUser(userId);
        int update = oaCWorkOrderMapper.updateById(oaCWorkOrder);
        if(update < 1){
            throw PangException.create(EErrorCode.addError);
        }
            LambdaQueryWrapper<OaCOrderPersonal> wrapper = new LambdaQueryWrapper<OaCOrderPersonal>()
                    .eq(OaCOrderPersonal::getOrderNo, oaCWorkOrder.getOrderNo())
                    .eq(OaCOrderPersonal::getDeleted,0);
            OaCOrderPersonal orderPersonal = oaCOrderPersonalMapper.selectOne(wrapper);
            //撤销成功 向司机发送消息
            OaSysMessage oaSysMessage = new OaSysMessage();
            oaSysMessage.setMessageType(2);
            oaSysMessage.setDriverId(orderPersonal.getDriverId());
            oaSysMessage.setCreateUser(userId);
            oaSysMessage.setUpdateUser(userId);
            //向freeze中写入数据
            Date date = new Date();
            OaDFreeze oaDFreeze = new OaDFreeze();
            oaDFreeze.setFreezeId(IDUtil.nextId());
            oaDFreeze.setOrderNumber(oaCWorkOrder.getOrderNo());
            oaDFreeze.setDriverId(oaCWorkOrder.getDriverId());
            oaDFreeze.setFreezeDate(date);
            oaDFreeze.setTag(TokenUtil.getTag());
            oaDFreeze.setCreateUser(userId);
            oaDFreeze.setCreateTime(date);
            oaDFreeze.setUpdateUser(userId);
            oaDFreeze.setUpdateTime(date);
            if(oaCWorkOrder.getAmount().doubleValue() < 0){
                //向司机发送扣款撤销信息
                oaSysMessage.setMessageTitle(MessageConstant.DEDUCT_MONEY);
                oaSysMessage.setPushCode(EBillType.DEDUCT_MONEY.getIdenifition());
                oaSysMessage.setMessageContent(
                        MessageConstant.PUBLIC_MSG_NO+
                                oaCWorkOrder.getOrderNo()+
                                MessageConstant.PUBLIC_MSG_DE+
                                MessageConstant.FONT_HEAD+
                                oaCWorkOrder.getAmount().doubleValue()+
                                MessageConstant.FONT_TAIL+
                                MessageConstant.PUBLIC_MSG_K+
                                MessageConstant.PUBLIC_MSG_C+
                                MessageConstant.PUBLIC_MSG_T
                );
                oaDFreeze.setBillTypeDesc(DEDUCT_MONEY_CANCEL_TYPE);
                oaDFreeze.setFreezeAmount(new BigDecimal(Math.abs(oaCWorkOrder.getAmount().doubleValue())));
            }else{
                //向司机发送补款撤销信息
                oaSysMessage.setMessageTitle(MessageConstant.FILLING_MONEY);
                oaSysMessage.setPushCode(EBillType.FILLING_MONEY.getIdenifition());
                oaSysMessage.setMessageContent(
                        MessageConstant.PUBLIC_MSG_NO+
                                oaCWorkOrder.getOrderNo()+
                                MessageConstant.PUBLIC_MSG_DE+
                                MessageConstant.FONT_HEAD+
                                oaCWorkOrder.getAmount().doubleValue()+
                                MessageConstant.FONT_TAIL+
                                MessageConstant.PUBLIC_MSG_B+
                                MessageConstant.PUBLIC_MSG_C+
                                MessageConstant.PUBLIC_MSG_T
                );
                oaDFreeze.setBillTypeDesc(FILLING_MONEY_CANCEL_TYPE);
                oaDFreeze.setFreezeAmount(new BigDecimal(-Math.abs(oaCWorkOrder.getAmount().doubleValue())));
            }
            iOaSysMessageService.saveMessage(oaSysMessage);
            int insert = oaDFreezeMapper.insert(oaDFreeze);
        return Rv.wrap(EErrorCode.success,insert);
    }

    @Override
    public Rv getWorkSheetByOrderNo(String orderNo) {
        //根据订单号查询工单信息
        String tag = TokenUtil.getTag();
        long userId = TokenUtil.getTokenUserId();
        if(CheckUtil.objIsEmpty(tag,userId)){
            throw PangException.create(EErrorCode.missingArg);
        }
        if(CheckUtil.strIsEmpty(orderNo)){
            throw PangException.create(EErrorCode.missingArg);
        }
        List<OaCWorkOrder> workOrderList = oaCWorkOrderMapper.selectList(Qw.create().eq(OaCWorkOrder.DELETED, 0).eq(OaCWorkOrder.ORDER_NO, orderNo));
        return Rv.wrap(EErrorCode.success,workOrderList);
    }

    /**
     * 根据条件分页查询工单列表
     * @param conditions
     * @return
     */
    @Override
    @Transactional
    public Rv getWorkOrderListByConditions(WorkSheetGetByConditions conditions) {
        if(CheckUtil.objIsEmpty(conditions)){
            throw PangException.create(EErrorCode.missingArg);
        }
        IPage<OaCWorkOrder> iPage = new Page<>();
        iPage.setCurrent(conditions.getCurrent());
        iPage.setSize(conditions.getPageSize());
        QueryWrapper<OaCWorkOrder> queryWrapper = getOaCWorkOrderQueryWrapper(conditions);
        IPage<OaCWorkOrder> resPage = oaCWorkOrderMapper.selectPage(iPage, queryWrapper);
        return Rv.wrap(EErrorCode.success,resPage);
    }

    /**
     * 新增工单信息
     * @param oaCWorkOrder
     * @return
     */
    @Override
    public Rv addWorkSheetInfo(OaCWorkOrder oaCWorkOrder) {
        TokenUser user = TokenUtil.getTokenUser();
        Long userId = user.getTokenUserId();
        OaSysUser oaSysUser = userMapper.selectOne(Qw.create().eq(OaSysUser.SYS_USER_ID, userId));

        if(CheckUtil.objIsEmpty(userId,oaSysUser.getName())){
            throw PangException.create(EErrorCode.missingArg);
        }
        if(CheckUtil.objIsEmpty(oaCWorkOrder.getOrderNo())){
            throw PangException.create(EErrorCode.missingArg);
        }
        oaCWorkOrder.setCreateUser(userId);
        oaCWorkOrder.setCreatorName(oaSysUser.getName());
        oaCWorkOrder.setUpdateUser(userId);
        oaCWorkOrder.setWorkOrderId(IDUtil.nextId());
        //根据订单编号查询订单
        LambdaQueryWrapper<OaCOrderPersonal> wrapper = new LambdaQueryWrapper<OaCOrderPersonal>()
                .eq(OaCOrderPersonal::getOrderNo, oaCWorkOrder.getOrderNo())
                .eq(OaCOrderPersonal::getDeleted,0);
        OaCOrderPersonal orderPersonal = oaCOrderPersonalMapper.selectOne(wrapper);
        if(CheckUtil.objIsEmpty(orderPersonal)){
            throw PangException.create(EErrorCode.addError);
        }
        OaDUser oaDUser = oaDUserMapper.selectOne(Qw.create().eq(OaDUser.DRIVER_ID, oaCWorkOrder.getDriverId()));
        if(CheckUtil.objIsEmpty(oaDUser)){
            throw PangException.create(EErrorCode.addError);
        }
        oaCWorkOrder.setOfficeId(Long.valueOf(orderPersonal.getOfficeId()));
        oaCWorkOrder.setDriverName(oaDUser.getDriverName());
        oaCWorkOrder.setOrderTime(orderPersonal.getAppointment());
        OaSysVehicle oaSysVehicle = oaSysVehicleMapper.selectOne(new QueryWrapper<OaSysVehicle>().eq(OaSysVehicle.VEHICLE_ID, orderPersonal.getVehicleId()));
        if(CheckUtil.objIsEmpty(oaSysVehicle)){
            throw PangException.create(EErrorCode.addError);
        }
        oaCWorkOrder.setVehNo(oaSysVehicle.getVehNo());
        OaSysOffice oaSysOffice = oaSysOfficeMapper.selectOne(new QueryWrapper<OaSysOffice>().eq(OaSysOffice.OFFICE_ID, orderPersonal.getOfficeId()));
        if(CheckUtil.objIsEmpty(oaSysOffice)){
            throw PangException.create(EErrorCode.addError);
        }
        oaCWorkOrder.setOfficeName(oaSysOffice.getName());
        oaCWorkOrder.setCreateTime(new Date());
        oaCWorkOrder.setUpdateTime(new Date());
        oaCWorkOrder.setDriverId(oaDUser.getDriverId());
        int insertWorkOrder = oaCWorkOrderMapper.insert(oaCWorkOrder);
        if(insertWorkOrder < 1){
            throw PangException.create(EErrorCode.addError);
        }
        //向freeze中写入数据
        Date date = new Date();
        OaDFreeze oaDFreeze = new OaDFreeze();
        oaDFreeze.setFreezeId(IDUtil.nextId());
        oaDFreeze.setOrderNumber(oaCWorkOrder.getOrderNo());
        oaDFreeze.setDriverId(oaCWorkOrder.getDriverId());
        oaDFreeze.setFreezeAmount(oaCWorkOrder.getAmount());
        oaDFreeze.setFreezeDate(date);
        oaDFreeze.setTag(TokenUtil.getTag());
        oaDFreeze.setCreateUser(userId);
        oaDFreeze.setCreateTime(date);
        oaDFreeze.setUpdateUser(userId);
        oaDFreeze.setUpdateTime(date);
        //给司机APP上显示，并进入司机账号的计算
        OaSysMessage oaSysMessage = new OaSysMessage();
        oaSysMessage.setMessageType(2);
        oaSysMessage.setDriverId(orderPersonal.getDriverId());
        oaSysMessage.setCreateUser(userId);
        oaSysMessage.setUpdateUser(userId);
        if(oaCWorkOrder.getAmount().doubleValue() < 0){
            //向司机端首页展示有罚款
            oaSysMessage.setMessageTitle(MessageConstant.DEDUCT_MONEY);
            oaSysMessage.setPushCode(EBillType.DEDUCT_MONEY.getIdenifition());
            oaSysMessage.setMessageContent(
                    MessageConstant.YOU_HAVE+
                    MessageConstant.FONT_HEAD+
                    oaCWorkOrder.getAmount().doubleValue()+
                    MessageConstant.FONT_TAIL+
                    MessageConstant.PUBLIC_MSG_K+","+
                    MessageConstant.PUBLIC_MSG_NO+
                    oaCWorkOrder.getOrderNo()+
                    MessageConstant.PUBLIC_MSG_T
                    );
            oaDFreeze.setBillTypeDesc(DEDUCT_MONEY_TYPE);
        }else{
            //向司机发送有补款
            oaSysMessage.setMessageTitle(MessageConstant.FILLING_MONEY);
            oaSysMessage.setPushCode(EBillType.FILLING_MONEY.getIdenifition());
            oaSysMessage.setMessageContent(
                    MessageConstant.YOU_HAVE+
                            MessageConstant.FONT_HEAD+
                            oaCWorkOrder.getAmount().doubleValue()+
                            MessageConstant.FONT_TAIL+
                            MessageConstant.PUBLIC_MSG_B+","+
                            MessageConstant.PUBLIC_MSG_NO+
                            oaCWorkOrder.getOrderNo()+
                            MessageConstant.PUBLIC_MSG_T
            );
            oaDFreeze.setBillTypeDesc(FILLING_MONEY_TYPE);
        }
        iOaSysMessageService.saveMessage(oaSysMessage);
        int insert = oaDFreezeMapper.insert(oaDFreeze);
        return Rv.wrap(EErrorCode.success,insert);
    }

    /**
     * DiDi新建工单
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getCreateWorkOrder(CreateWorkOrderParam param) {
        try {
            //创建系统工单信息
            OaSysWorksheet oaSysWorksheet = this.createOaSysWorksheet(param);
            //创建合力工单信息
            OaSysWorksheetEntity oaSysWorksheetEntity = this.createWorksheetEntity(oaSysWorksheet);

            //创建接口操作记录
            Long worksheetId = IDUtil.nextId();
            oaSysWorksheetOperateService.createWorksheetOperate(param,
                    worksheetId,
                    "create",
                    "didi",
                    "hollycrm");

            // 调用合力创建工单
            Rv ticket = workSheetToHeLiService.createTicket(oaSysWorksheetEntity);
            String heliWorksheetId = ticket.getData().toString();

            oaSysWorksheet.setWorksheetId(worksheetId);
            oaSysWorksheet.setHeliWorksheetId(heliWorksheetId);
            oaSysWorksheet.setDidiWorksheetId(param.getWorksheet_id());
            // 创建系统工单
            oaSysWorksheetMapper.insert(oaSysWorksheet);

            CreateWorkResult createWorkResults = new CreateWorkResult();
            createWorkResults.setWorksheet_id(heliWorksheetId);

            return DiDiRv.wrap(EDiDiErrorCode.success, createWorkResults);
        } catch (WorksheetException ex) {
            return DiDiRv.wrapErrorCode(EDiDiErrorCode.createWorksheetFailed);
        } catch (Exception ex) {
            return DiDiRv.wrapErrorCode(EDiDiErrorCode.unKnow);
        }
    }

    /**
     * 更新工单
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getUpdateWorkOrder(UpdateWorkOrderParam param) {
        try {
            // 获取工单信息
            OaSysWorksheet worksheet = iOaSysWorksheetService.queryWorksheetByHeliWorksheetId(param.getWorksheet_id());

            if (CheckUtil.objIsEmpty(worksheet)) {
                log.info("未获取到工单信息，工单id:{}", param.getWorksheet_id());
                return DiDiRv.wrapErrorCode(EDiDiErrorCode.getWorksheetFailed);
            }

            //创建接口操作记录
            oaSysWorksheetOperateService.createWorksheetOperate(param,
                    worksheet.getWorksheetId(),
                    "update",
                    "didi",
                    "hollycrm");

            // 调用合力
            UpdateTicketStatusEntity entity = new UpdateTicketStatusEntity();
            entity.setThreeContent(param.getContent());
            entity.setThreeStatus(String.valueOf(param.getAction()));
            entity.setTicketId(worksheet.getHeliWorksheetId());
            entity.setThreeTime(String.valueOf(System.currentTimeMillis()));
            Rv rv = workSheetToHeLiService.updateTicketStatus(entity);

            if (!rv.getSuccess()) {
                throw DiDiException.create(EDiDiErrorCode.updateWorksheetFailed);
            }

            return DiDiRv.wrapSuccessCode(EDiDiErrorCode.success);
        } catch (WorksheetException ex) {
            return DiDiRv.wrapErrorCode(EDiDiErrorCode.updateWorksheetFailed);
        } catch (Exception ex) {
            return DiDiRv.wrapErrorCode(EDiDiErrorCode.unKnow);
        }
    }

    /**
     * 工单加急接口
     *
     * @return
     */
    @Override
    public DiDiRv getWorkOrderUrgent(WorkOrderUrgentParam param) {
        try {
            // 获取工单信息
            OaSysWorksheet worksheet = iOaSysWorksheetService.queryWorksheetByHeliWorksheetId(param.getWorksheet_id());

            if (worksheet == null) {
                log.info("未获取到工单信息，工单id:{}", param.getWorksheet_id());
                return DiDiRv.wrapErrorCode(EDiDiErrorCode.getWorksheetFailed);
            }

            //创建接口操作记录
            oaSysWorksheetOperateService.createWorksheetOperate(param,
                    worksheet.getWorksheetId(),
                    "urgent",
                    "didi",
                    "hollycrm");

            // 调用合力
            UrgentTicketEntity urgentTicket = new UrgentTicketEntity();
            urgentTicket.setUrgentStatus(param.getLevel().toString());
            urgentTicket.setUrgentContent(param.getContent());
            urgentTicket.setTicketId(String.valueOf(worksheet.getHeliWorksheetId()));
            urgentTicket.setUrgentStatus(String.valueOf(System.currentTimeMillis()));
            Rv rv = workSheetToHeLiService.urgentTicket(urgentTicket);
            if (!rv.getSuccess()) {
                throw DiDiException.create(EDiDiErrorCode.ugWorksheetFailed);
            }
            return DiDiRv.wrapSuccessCode(EDiDiErrorCode.success);
        } catch (WorksheetException ex) {
            return DiDiRv.wrapErrorCode(EDiDiErrorCode.ugWorksheetFailed);
        } catch (Exception ex) {
            return DiDiRv.wrapErrorCode(EDiDiErrorCode.unKnow);
        }
    }

    @Override
    public Rv getLoginSynchronous(LoginSynchronousParam param) {
        return  workSheetToHeLiService.getLoginSynchronous(param);
    }

    /**
     * 客服角色同步接口
     *
     * @return
     */
    @Override
    public Rv getRoleSynchronous(RoleSynchronousParam param) {
        return  workSheetToHeLiService.getRoleSynchronous(param);
    }


    /**
     * 创建合力
     *
     * @param oaSysWorksheet
     * @return
     */
    private OaSysWorksheetEntity createWorksheetEntity(OaSysWorksheet oaSysWorksheet) {
        OaSysWorksheetEntity entity = new OaSysWorksheetEntity();
        entity.setOrderNo(oaSysWorksheet.getOrderNo());
        entity.setTicketNo(oaSysWorksheet.getTicketNo());
        entity.setScene3(oaSysWorksheet.getDictId());
        entity.setFeedbackPerson(oaSysWorksheet.getFeedbackPerson());
        entity.setFeedbackPhone(oaSysWorksheet.getFeedbackPhone());
        entity.setFeedbackParty(oaSysWorksheet.getFeedbackParty());
        entity.setHandleContent(oaSysWorksheet.getContent());
        entity.setThreeStatus(oaSysWorksheet.getTicketStatus());
        entity.setTicketStatus("0");
        entity.setTicketFrom("didi");
        entity.setCityCode(oaSysWorksheet.getDistrict());
        return entity;
    }

    /**
     * 创建系统工单数据
     *
     * @param param
     * @return
     */
    private OaSysWorksheet createOaSysWorksheet(CreateWorkOrderParam param) {
        // 查询城市
        List<OaSysArea> areaList = getCityCode(param.getDistrict());
        if (CheckUtil.collectionIsEmpty(areaList)) {
            throw DiDiException.create(EDiDiErrorCode.parameterError);
        }
        String code = areaList.get(0).getAdCode();

        OaSysWorksheet worksheet = new OaSysWorksheet();
        worksheet.setWorksheetSource("didi");
        worksheet.setOrderId("");
        // 滴滴传递字段
        worksheet.setOrderNo(param.getOrder_id());
        worksheet.setFeedbackPerson(param.getCustomer_name());
        worksheet.setFeedbackPhone(param.getPhone());
        worksheet.setFeedbackParty(param.getCustomer_type().toString());
        worksheet.setDistrict(param.getDistrict());
        worksheet.setContent(param.getContent());
        worksheet.setDictId(param.getDict_id());
        worksheet.setCustomerName(param.getCustomer_name());
        worksheet.setCustomerType(String.valueOf(param.getCustomer_type()));
        worksheet.setWfrole(param.getWfrole());
        worksheet.setTicketStatus(param.getStatus().toString());

        worksheet.setQuestionType("");
        worksheet.setPhone(param.getPhone());
        worksheet.setExtra(param.getExtra());
        worksheet.setLevel("1");
        worksheet.setCreateTime(new Date());
        worksheet.setCreateUser("");
        worksheet.setQuestionType("");
        worksheet.setCityCode("");
        worksheet.setTicketNo("");
        worksheet.setCityCode(code);

        return worksheet;
    }

    /**
     * 获取城市CODE
     *
     * @param cityId
     * @return
     */
    public List<OaSysArea> getCityCode(String cityId) {
        QueryWrapper<DidiSysArea> diAreaQueryWrapper = new QueryWrapper<>();
        diAreaQueryWrapper.eq(DidiSysArea.CITY_CODE, cityId);
        List<DidiSysArea> diAreaList = didiSysAreaMapper.selectList(diAreaQueryWrapper);
        List<OaSysArea> areaList = new ArrayList<>();
        if (!diAreaList.isEmpty()) {
            QueryWrapper<OaSysArea> areaQueryWrapper = new QueryWrapper<>();
            areaQueryWrapper.like(OaSysArea.NAME, diAreaList.get(0).getName());
            // 查询type为3的市，否则容易出现混乱
            areaQueryWrapper.eq(OaSysArea.TYPE, ParameterEnum.THREE.getType());
            areaList = oaSysAreaMapper.selectList(areaQueryWrapper);
        }
        return areaList;
    }

    private QueryWrapper<OaCWorkOrder> getOaCWorkOrderQueryWrapper(WorkSheetGetByConditions conditions) {
        QueryWrapper<OaCWorkOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaCWorkOrder.DELETED,0).orderByDesc(OaCWorkOrder.CREATE_TIME);
        if(CheckUtil.objIsNotEmpty(conditions.getDriverName())){
            queryWrapper.like(OaCWorkOrder.DRIVER_NAME,conditions.getDriverName());
        }
        if(CheckUtil.objIsNotEmpty(conditions.getVehNo())){
            queryWrapper.eq(OaCWorkOrder.VEH_NO,conditions.getVehNo());
        }
        if(CheckUtil.objIsNotEmpty(conditions.getOrderNo())){
            queryWrapper.eq(OaCWorkOrder.ORDER_NO,conditions.getOrderNo());
        }
        if(CheckUtil.objIsNotEmpty(conditions.getOfficeId())){
            queryWrapper.eq(OaCWorkOrder.OFFICE_ID,conditions.getOfficeId());
        }
        if(CheckUtil.objIsNotEmpty(conditions.getCreator())){
            queryWrapper.like(OaCWorkOrder.CREATOR_NAME,conditions.getCreator());
        }
        if(CheckUtil.objIsNotEmpty(conditions.getCETimer(),conditions.getCSTimer())){
            queryWrapper.ge(OaCWorkOrder.CREATE_TIME,conditions.getCSTimer());
            queryWrapper.le(OaCWorkOrder.CREATE_TIME,conditions.getCETimer());
        }
        if(CheckUtil.objIsNotEmpty(conditions.getOETimer(),conditions.getOSTimer())){
            queryWrapper.ge(OaCWorkOrder.CREATE_TIME,conditions.getOSTimer());
            queryWrapper.le(OaCWorkOrder.CREATE_TIME,conditions.getOETimer());
        }
        return queryWrapper;
    }
}
